package com.shangyueshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.mapper.FixedCostMapper;
import com.shangyueshang.model.FixedCost;
import com.shangyueshang.request.FixedCostDTO;
import com.shangyueshang.request.PageReq;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.response.PageResult;
import com.shangyueshang.service.FixedCostService;
import com.shangyueshang.utils.MyPageHelper;
import com.shangyueshang.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/17 17:03
 * @version: v1.0.0
 */
@Slf4j
@Service
public class FixedCostServiceImpl extends ServiceImpl<FixedCostMapper, FixedCost> implements FixedCostService {
	
	@Override
	public PageResult<FixedCost> findPage(PageReq pageReq) {
		QueryWrapper<FixedCost> queryWrapper =
				new QueryWrapper<FixedCost>()
						.orderByDesc(SysConstants.trade_month);
		pageReq.getLineParams().forEach(queryWrapper::eq);
		PageInfo<FixedCost> pageInfo =
				PageHelper.startPage(
						pageReq.getPageNum(),
						pageReq.getPageSize()
				).doSelectPageInfo(
						() -> super.list(queryWrapper)
				);
		return MyPageHelper.getPageResult(pageInfo);
	}
	
	@Override
	public HttpResult<Void> saveUpdate(FixedCostDTO req) {
		FixedCost fixedCost = super.getOne(
				new QueryWrapper<FixedCost>()
						.eq(
								SysConstants.trade_month,
								req.getTradeMonth()
						)
		);
		if (Objects.isNull(fixedCost)) {
			fixedCost = new FixedCost();
			fixedCost.setCreator(SecurityUtil.getUsername());
		}
		BeanUtils.copyProperties(req, fixedCost);
		fixedCost.setLastUpdator(SecurityUtil.getUsername());
		try {
			super.saveOrUpdate(fixedCost);
		} catch (DuplicateKeyException e) {
			log.error("save fixed cost error:{}", e.getMessage());
			return HttpResult.fail(req.getTradeMonth().toString() + " 月份的数据已存在，请勿重复添加");
		}
		return HttpResult.ok();
	}
}
